package com.cuizhang.demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.ll.core.action.QueryAction;
import com.ll.core.magzine.model.bean.Article;
import com.ll.core.magzine.model.bean.Period;
import com.ll.core.util.CommonTool;
import com.ll.core.util.JSONTool;
import com.ll.core.util.TypeTokens;
import com.ll.core.view.util.ViewUtil;

public class StageActivity extends Activity {

	private final static int DIALOG_LOADING = 1001;
	private ProgressDialog dialog;
	/**
	 * 重要新闻
	 */
	private ListView importListView;
	private ListView normalListView;
	private String[] dates;
	int current = 0;
	private Period currentPeriod;
	private ArticleArrayAdapter<Article> importArrayAdapter;
	private ArticleArrayAdapter<Article> normalArrayAdapter;
	private ImageView imageView;
	private TextView tv1;
	private TextView tv2;
	private TextView tv3;
	
	private void getIntentDatas() {
		Intent i = getIntent();
		this.currentPeriod = (Period)JSONTool.stringToObject(i.getStringExtra("period"),TypeTokens.PERIOD);
		current = i.getIntExtra("index", 0);
	}
	
	private void initHeader(){
		imageView = (ImageView)findViewById(R.id.cover);
		tv1 = (TextView)findViewById(R.id.tv1);
		tv2 = (TextView)findViewById(R.id.tv2);
		tv3 = (TextView)findViewById(R.id.tv3);
		
		loadHeaderData();
	}
	
	private void loadHeaderData(){
		//getResources().getDrawable(sourceIds[current]
		//imageView.setImageDrawable(getResources().getDrawable(R.drawable.p1));
		Log.d("cover_id", "当前封面路径"+currentPeriod.getCover_id());
		imageView.setImageBitmap(ViewUtil.loadImage(currentPeriod.getCover_id()));
		tv1.setText(CommonTool.DateToString(currentPeriod.getPublish_time(),"yyyy年MM月dd日"));
		tv2.setText("年度期号："+this.currentPeriod.getYear_period());
		tv3.setText("总第"+this.currentPeriod.getPeriod()+"期");
	}
	/**
	 * 初始化按钮事件
	 */
	private void initButtonEvent(){
		Button btn = (Button) findViewById(R.id.back);
		btn.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				finish();
			}
		});

		ImageView btnLeft = (ImageView) findViewById(R.id.search_stock_left);
		btnLeft.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				if (current > 0) {
					current--;
				}
				loadHeaderData();
			}
		});

		ImageView btnRight = (ImageView) findViewById(R.id.search_stock_right);
		btnRight.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				if (current < dates.length - 1) {
					current++;
				}
				loadHeaderData();
			}
		});
	}


	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.stage_all);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_text);
		this.importListView = (ListView)this.findViewById(R.id.importnews);
		this.normalListView = (ListView)this.findViewById(R.id.normalnews);
	
		getIntentDatas();
		initHeader();
		initButtonEvent();
		//加载相应的新闻
		loadArticles();
		this.importListView.setOnItemClickListener(new OnItemClickListenerImpl(this.importArrayAdapter));
		this.normalListView.setOnItemClickListener(new OnItemClickListenerImpl(this.normalArrayAdapter));
	}

	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_LOADING:
			dialog = new ProgressDialog(this);
			dialog.setMessage("数据加载中......");
			dialog.setIndeterminate(true);
			return dialog;

		}
		return super.onCreateDialog(id);
	}
	/**
	 * 加载文章
	 */
	private void loadArticles(){
		new ProgressTask().execute();
	}
	
	private void queryArticles(){
		List<Article> articles = null;
		try {
			if(this.currentPeriod == null){
				return;
			}
			articles = QueryAction.getInstance().queryArticlesByPeriod(String.valueOf(this.currentPeriod.getPeriod()));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return;
		}
		bindArticlesToAdapter(this.importListView,this.importArrayAdapter,splitArticles(articles,"1"));
		bindArticlesToAdapter(this.normalListView,this.normalArrayAdapter,splitArticles(articles,"2"));

	}
	
	/**
	 * 将内容和listview绑定
	 * @param listview
	 * @param arrayAdapter
	 * @param articles
	 */
	private void bindArticlesToAdapter(ListView listview,ArrayAdapter<Article> arrayAdapter,List<Article> articles){
		if(articles == null){
			return;
		}
		if(articles.size() == 0){
			Log.i("INFO", "没有返回数据!");
		}
		if (arrayAdapter == null) {
			arrayAdapter = new ArticleArrayAdapter<Article>(
					StageActivity.this, R.layout.stage_all_row, articles);
			listview.setAdapter(arrayAdapter);
			ViewUtil.setListViewHeightBasedOnChildren(listview);
		} else {

			arrayAdapter.clear();
			for (Article a : articles) {
				arrayAdapter.add(a);
			}
			//LastPeriodActivity.this.lv.setSelection(0);
		}
	}
	/**
	 * 拆分新闻
	 * @param articles 文章内容
	 * @param type 类型 1--重要信息 2--一般新闻
	 * @return
	 */
	private List<Article> splitArticles(List<Article> articles,String type){
		List<Article> resultArticles = new ArrayList<Article>();
		
		for(Article a : articles){
			if(a.getType().equals(type)){
				resultArticles.add(a);
			}
		}
		return resultArticles;
	}
private class ProgressTask extends AsyncTask<Void, Void, Void> {

		

		@Override
		protected void onPreExecute() {
			showDialog(DIALOG_LOADING);
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			queryArticles();
			removeDialog(DIALOG_LOADING);
			super.onPostExecute(result);
		}
	}


	/**
	 * 读取配置文件
	 * 
	 * @return
	 */
	private String getFromRaw(int fileName) {
		BufferedReader br = null;
		InputStream is = null;
		StringBuffer sb = null;
		try {
			is = getResources().openRawResource(fileName);
			br = new BufferedReader(new InputStreamReader(is));
			sb = new StringBuffer();
			String line = null;
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (is != null) {
				try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}
		return sb.toString();
	}
	
	public static class ViewHolder {
		public TextView title;// 发布时间
		public TextView auther;// 发布期别
		public ImageView image;// 封面
		// public TextView lastPublisher;
	}

	private class ArticleArrayAdapter<T> extends ArrayAdapter {
		private int ResourceId;
		private LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		public ArticleArrayAdapter(Context context, int textViewResourceId,
				List objects) {
			super(context, textViewResourceId, objects);
			this.ResourceId = textViewResourceId;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = mInflater.inflate(ResourceId, null);
				holder = new ViewHolder();
				holder.title = (TextView) convertView.findViewById(R.id.title);
				holder.auther = (TextView) convertView
						.findViewById(R.id.auther);
				holder.image =(ImageView)convertView.findViewById(R.id.app_icon);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			Article article = (Article) this.getItem(position);
			holder.title.setText(article.getTitle());// 发布时间
			System.out.println(article.getPublisher());
			holder.auther.setText(article.getPublisher()+"/文");// 发布年度
			holder.image.setImageBitmap(ViewUtil.loadImage(article.getImage_id()));
			return convertView;
		}
	};
	
	private class OnItemClickListenerImpl implements OnItemClickListener{
		private ArticleArrayAdapter<Article> articleAdapter;
		
		public OnItemClickListenerImpl(ArticleArrayAdapter<Article> ad){
			this.articleAdapter =ad;
		}
		@Override
		public void onItemClick(AdapterView<?> av, View view, int position,
				long id) {
			ArticleArrayAdapter<Article> articleAdapter = (ArticleArrayAdapter)av.getAdapter();
			Article article = (Article)articleAdapter.getItem(position);
			Intent i = new Intent(StageActivity.this, ArticlePage.class);
			i.putExtra("article", JSONTool.ObjectToJSON(article));
			startActivity(i);
		}
		
	}

}
